//
//  HomeViewController.m
//  NuwaRobot
//
//  Created by Kendama on 2017/12/1.
//  Copyright © 2017年 Kendama. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeCollectionViewCell.h"
#import "RemindViewController.h"
#import "SettingViewController.h"
#import "PhoneViewController.h"
#import "HomeControlViewController.h"
#import "NewsViewController.h"
#import "BindDeviceView.h"
#import "ScanDeviceViewController.h"
#import "HomeView.h"
#import "FullScreenViewController.h"
#import "ChooseContactsViewController.h"
#import "GetUnreadApi.h"
#import "GetUserDeviceApi.h"
#import "MusicPlayView.h"
#import "MusicModel.h"
#import "FullScreenView.h"

@interface HomeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
// 监控全屏界面
//@property(nonatomic,strong) FullScreenView *fullScreenView;

@property(nonatomic,strong) BindDeviceView *bindDeviceView;
@property(nonatomic,strong) HomeView *homeView;
@property(nonatomic,strong) NSArray *dataSource;
@property(nonatomic,strong) FullScreenViewController *fullScreenViewController;
@property(nonatomic,copy) NSString *unread;

// 定时器
@property (nonatomic, strong)dispatch_source_t timer;
@property(nonatomic,assign) BOOL isTimer;
@property(nonatomic,strong)MusicModel *musicModel;

// 监控
@property (strong, nonatomic) __block EMCallConference *conference;
@property(nonatomic,copy) NSString *conferenceId;
@property(nonatomic,copy) NSString *streamId;
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    SAVE_OBJECT(@"0123456789abcdef", DEVICEMAC);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateXiMaLaYaData:) name:XiMaLaYa object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateMonitoringData:) name:Monitoring object:nil];

//    self.conferenceId = @"10.162.220.233#MP222760994888224768C1106";
//    self.streamId = @"rtc-1-ikc";
//    [self startMonitoring];
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self getNewsUnreadCount];
    [self getUserDevice];
    
    // 查询喜马拉雅播放状态
    [[DataManager sharedInstance] sendCode:@"1012" data:@{}];

//    NSLog(@"UID:%@",EXRACT_OBJECT(UID));
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:XiMaLaYa];
}

#pragma mark -- 定时刷新
- (void)startTiming {
    
    NSTimeInterval period = 1.0; //设置时间间隔
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(self.timer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(self.timer, ^{
        //在这里执行事件
        [self setNowDateString];
    });
    dispatch_resume(self.timer);
    self.isTimer = YES;
}

- (void)stopTiming
{
    if (self.timer)
    {
        dispatch_cancel(self.timer);
        self.isTimer = NO;
    }
}



#pragma mark --- 点击事件
- (void)didClickScanDeviceButton
{
    ScanDeviceViewController *vc = [ScanDeviceViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didClickFullScreenButton
{
//    __weak typeof(self) weakSelf = self;
    [[AppDelegate defaultService].window addSubview:self.fullScreenViewController.view];
    [[AppDelegate defaultService].window.rootViewController addChildViewController:self.fullScreenViewController];
    [self unsubscribeConferenceRemoteVideoView:self.fullScreenViewController.fullScreenView.videoView];
//    self.fullScreenViewController.fullScreenView.videoView = self.homeView.videoView;
    [self.fullScreenViewController startTiming];
}

// 全屏切换时取消原来的订阅再重新订阅
- (void)unsubscribeConferenceRemoteVideoView:(EMCallRemoteView *)remoteVideoView
{
    __weak typeof(self) weakSelf = self;
    [[EMClient sharedClient].conferenceManager unsubscribeConference:weakSelf.conference streamId:weakSelf.streamId completion:^(EMError *aError) {
        //code
        [[EMClient sharedClient].conferenceManager subscribeConference:weakSelf.conference streamId:weakSelf.streamId remoteVideoView:remoteVideoView completion:^(EMError *aError) {
            if (aError)
            {

            }
            else
            {
                
            }
        }];
    }];
}

- (void)didClickVideoCall
{
    ChooseContactsViewController *vc = [[ChooseContactsViewController alloc] init];
    vc.chooseType = VideoCall;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didClickPlayButton
{
//    [self hideMusicPlayView];
    if (_musicModel)
    {
        [[DataManager sharedInstance] sendCode:@"1011" data:@{@"album_id":_musicModel.album_id,@"index":_musicModel.index,@"state":@"0"}];
    }
}

#pragma mark -- 事件处理
- (void)getNewsUnreadCount
{
    GetUnreadApi *api = [[GetUnreadApi alloc] init];
    [api dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
        NSDictionary *dict = [request responseJSONObject];
        self.unread = dict[@"data"][@"number"];
        [self.homeView.collectionView reloadData];
    } failure:nil];
}

- (void)getUserDevice
{
    if ([EXRACT_OBJECT(DEVICEID) isEqualToString:@"0"] || !EXRACT_OBJECT(DEVICEID)) // 没有设备
    {
        GetUserDeviceApi *api = [[GetUserDeviceApi alloc] init];
        [api dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
            NSDictionary *dict = request.responseJSONObject[@"data"];
            NSString *deviceID = dict[@"device_id"];
            if ([deviceID intValue] == 0) // 没有绑定设备
            {
                self.bindDeviceView.hidden = NO;
            }
            else
            {
                self.bindDeviceView.hidden = YES;
            }
            SAVE_OBJECT(deviceID, DEVICEID);
            SAVE_OBJECT(dict[@"sn"], DEVICEMAC);
        } failure:nil];
    }
    else
    {
        self.bindDeviceView.hidden = YES;
    }

}

// 隐藏顶部音乐播放界面
- (void)hideMusicPlayView
{
    [self.homeView.musicPlayView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(_homeView.mas_top);
        make.left.right.mas_equalTo(self.homeView);
        make.height.mas_equalTo(px1920Height(120));
    }];
    [self.view bringSubviewToFront:self.navigationBar];
}

// 显示顶部音乐播放界面
- (void)showMusicPlayView
{
    [self.homeView.musicPlayView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self.homeView);
        make.height.mas_equalTo(px1920Height(120));
    }];
}

- (void)updateXiMaLaYaData:(NSNotification *)notification
{
    NSDictionary *dict = notification.userInfo;
    MusicModel *model = [[MusicModel alloc] init];
    [model setValuesForKeysWithDictionary:dict];
    self.musicModel = model;
    
    self.homeView.musicPlayView.titleLabel.text = dict[@"track_title"];
    if ([dict[@"state"] intValue] == 0) // 暂停
    {
        [self hideMusicPlayView];
        self.homeView.musicPlayView.playButton.selected = NO;
    }
    else
    {
        [self showMusicPlayView];
        self.homeView.musicPlayView.playButton.selected = YES;
    }
    NSLog(@"喜马拉雅---%@",dict);
}

- (void)updateMonitoringData:(NSNotification *)notification
{
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = notification.userInfo;
    self.conferenceId = dict[@"conference_id"];
    self.streamId = dict[@"stream_id"];
    
    [[EMClient sharedClient].conferenceManager joinConferenceWithConfId:_conferenceId password:@"" completion:^(EMCallConference *aCall, EMError *aError) {
        if (aError)
        {
            NSLog(@"加入会议--%@",aError.errorDescription);
        }
        else
        {
            weakSelf.conference = aCall;
//            EMCallRemoteView *remoteView = [[EMCallRemoteView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
//            [weakSelf.view addSubview:remoteView];
            
//            EMCallRemoteView *remoteView = weakSelf.homeView.videoView;
            // 订阅平板数据流
            [[EMClient sharedClient].conferenceManager subscribeConference:weakSelf.conference streamId:weakSelf.streamId remoteVideoView:weakSelf.homeView.videoView completion:^(EMError *aError) {
                if (aError)
                {
                    NSLog(@"视频数据--%@",aError.errorDescription);
                    //            NSString *message = [NSString stringWithFormat:NSLocalizedString(@"alert.conference.subFail", @"Sub stream-%@ failed!"), weakSelf.creater];
                    //            [weakSelf showHint:message];
                }
                else
                {
//                    [self.homeView.videoImageView addSubview:remoteView];
                    [weakSelf.homeView.activityIndicatorView stopAnimating];
                    weakSelf.homeView.tipsLabel.hidden = YES;
                }
            }];
        }
        
    }];
}

#pragma mark --- 监控
- (void)startMonitoring
{
    [[DataManager sharedInstance] sendCode:@"1051" data:@{@"uid":EXRACT_OBJECT(UID)}];

}

- (void)stopMonitoring
{
    [[EMClient sharedClient].conferenceManager unsubscribeConference:self.conference streamId:self.streamId completion:^(EMError *aError) {
        //code
        if (aError)
        {
            
        }
        else
        {
            
        }
    }];
    [[EMClient sharedClient].conferenceManager leaveConference:self.conference completion:nil];

}

#pragma mark --- tableView代理
#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSArray *array = self.dataSource.firstObject;
    return array.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HomeCollectionViewCell *cell = [HomeCollectionViewCell cellWithCollectionView:collectionView forIndexPath:indexPath];
    NSArray *titleArray = self.dataSource.firstObject;
    NSArray *imageArray = self.dataSource[1];

    cell.iconImageView.image = imageWithName(imageArray[indexPath.row]);
    cell.titleLabel.text = titleArray[indexPath.row];
    cell.badgeLabel.hidden = YES;
    if (indexPath.row == 5 && [self.unread intValue] != 0)
    {
        cell.badgeLabel.hidden = NO;
        cell.badgeLabel.text = self.unread;
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    HomeCollectionViewCell *cell = (HomeCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
    NSArray *imageArray = self.dataSource.lastObject;
    cell.iconImageView.image = imageWithName(imageArray[indexPath.row]);
}
- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    HomeCollectionViewCell *cell = (HomeCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
    NSArray *imageArray = self.dataSource[1];
    cell.iconImageView.image = imageWithName(imageArray[indexPath.row]);
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row)
    {
        case 0:
        {
            PhoneViewController *vc = [PhoneViewController new];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 1:
        {
            HomeControlViewController *vc = [HomeControlViewController new];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 2:
        {

            if (self.isTimer)
            {
                [self stopTiming];
                [self.homeView.activityIndicatorView stopAnimating];
                self.homeView.videoView.hidden = YES;
                [self stopMonitoring];
            }
            else
            {
                [self startTiming];
                self.homeView.tipsLabel.hidden = NO;
                [self.homeView.activityIndicatorView startAnimating];
                self.homeView.videoView.hidden = NO;
                [self startMonitoring];
            }
//            [self showMusicPlayView];
        }
            break;
        case 3:
        {
            SettingViewController *vc = [SettingViewController new];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 4:
        {
            RemindViewController *vc = [RemindViewController new];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 5:
        {
            NewsViewController *vc = [NewsViewController new];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        default:
            break;
    }
}

- (void)setNowDateString
{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.homeView.dateLabel.text = [formatter stringFromDate:date];
//        self.fullScreenViewController.
    });
}

#pragma mark --- 懒加载
- (HomeView *)homeView
{
    if(!_homeView)
    {
        UIView *superView = self.view;
        _homeView = [[HomeView alloc]init];
        [superView addSubview:_homeView];
        _homeView.collectionView.dataSource = self;
        _homeView.collectionView.delegate = self;
        [_homeView.fullscreenButton addTarget:self action:@selector(didClickFullScreenButton) forControlEvents:UIControlEventTouchUpInside];
        [_homeView.videoCallButton addTarget:self action:@selector(didClickVideoCall) forControlEvents:UIControlEventTouchUpInside];
        [_homeView.musicPlayView.playButton addTarget:self action:@selector(didClickPlayButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _homeView;
}


- (BindDeviceView *)bindDeviceView
{
    if(!_bindDeviceView)
    {
        UIView *superView = self.view;
        _bindDeviceView = [[BindDeviceView alloc]init];
        [superView addSubview:_bindDeviceView];
        [_bindDeviceView.scanButton addTarget:self action:@selector(didClickScanDeviceButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _bindDeviceView;
}

- (FullScreenViewController *)fullScreenViewController
{
    if(!_fullScreenViewController)
    {
        __weak typeof(self) weakSelf = self;
        _fullScreenViewController = [[FullScreenViewController alloc]init];
        _fullScreenViewController.closeFullBlock = ^{
            [weakSelf unsubscribeConferenceRemoteVideoView:weakSelf.homeView.videoView];
        };
    }
    return _fullScreenViewController;
}


- (NSArray *)dataSource
{
    if (!_dataSource)
    {
        _dataSource = @[@[@"拨打电话",@"家居控制",@"实时监控",@"设置",@"提醒",@"消息"],@[@"iPhone",@"home",@"monitoring",@"set",@"remind",@"news"],@[@"iPhone_pre",@"home_pre",@"monitoring_pre",@"set_pre",@"remind_pre",@"news_pre"]];
    }
    return _dataSource;
}


- (void)masLayoutSubview
{
    __weak UIView *superView = self.view;
    
    [self.homeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.left.right.bottom.mas_equalTo(superView);
    }];

    [self setNoFullView:self.homeView];
    
    [self.bindDeviceView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.left.right.bottom.mas_equalTo(superView);
    }];
    
    [superView bringSubviewToFront:self.navigationBar];
    
//    self.bindDeviceView.hidden = YES;
}


- (void)setNavigationStyle
{
    [self setLeftButtonImage:nil];
    [self setNavigationBarTitle:@"小天机器人"];
    self.navigationBar.backgroundColor = rgba(6,27,56,1);
}

@end
